package net.tv90.volunteerserveradmin.service;

import jakarta.annotation.Resource;
import net.tv90.volunteerserveradmin.dao.*;
import net.tv90.volunteerserveradmin.exception.ServiceException;
import net.tv90.volunteerserveradmin.model.domain.GradeSubmission;
import net.tv90.volunteerserveradmin.model.domain.Student;
import net.tv90.volunteerserveradmin.model.domain.Teacher;
import net.tv90.volunteerserveradmin.model.domain.VolunteerProject;
import net.tv90.volunteerserveradmin.model.dto.GradeSubmissionDTO;
import net.tv90.volunteerserveradmin.model.vo.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class GradeSubmissionService {

    @Resource
    private GradeSubmissionRepository gradeSubmissionRepository;
    @Resource
    private VolunteerProjectRelationRepository volunteerProjectRelationRepository;
    @Resource
    private ProjectTeacherRelationRepository projectTeacherRelationRepository;
    @Resource
    private VolunteerProjectRepository volunteerProjectRepository;
    @Resource
    private TeacherRepository teacherRepository;
    @Resource
    private StudentRepository studentRepository;

    public GradeVO queryStudentGrade(Long studentId, Long projectId) {
        // 验证学生是否参与该志愿活动
        boolean isStudentInProject = volunteerProjectRelationRepository.existsByVolunteerIdAndProjectId(studentId, projectId);
        if (!isStudentInProject) {
            throw new ServiceException("该学生未参与该志愿活动，无法查询评分信息");
        }
        // 查询评分记录
        List<GradeSubmission> gradeSubmissions = gradeSubmissionRepository.findByVolunteerIdAndProjectId(studentId, projectId);
        if (gradeSubmissions.isEmpty()) {
            throw new ServiceException("暂未评分");
        }

        double totalGrade = 0;
        List<GradeSubmissionVO> results = new ArrayList<>();
        for (GradeSubmission submission : gradeSubmissions) {
            Student student = studentRepository.findById(submission.getVolunteerId())
                    .orElseThrow(() -> new ServiceException("学生id不存在"));
            Teacher teacher = teacherRepository.findById(submission.getTeacherId())
                    .orElse(Teacher.newTeacher());
            VolunteerProject project = volunteerProjectRepository.findById(submission.getProjectId())
                    .orElseThrow(() -> new ServiceException("志愿活动id不存在"));
            StudentVO studentVO = StudentVO.builder()
                    .studentId(student.getId())
                    .name(student.getName())
                    .build();
            TeacherVO teacherVO = TeacherVO.builder()
                    .teacherId(teacher.getId())
                    .name(teacher.getName())
                    .build();
            VolunteerProjectVO projectVO = VolunteerProjectVO.builder()
                    .id(project.getId())
                    .title(project.getTitle())
                    .build();
            GradeSubmissionVO vo = GradeSubmissionVO.builder()
                    .id(submission.getId())
                    .project(projectVO)
                    .student(studentVO)
                    .teacher(teacherVO)
                    .comments(submission.getComments())
                    .score(submission.getScore())
                    .build();
            results.add(vo);
            totalGrade += submission.getScore();
        }
        totalGrade /= results.size();
        // 构造返回结果
        return GradeVO.builder()
                .gradeSubmissions(results)
                .totalGrade(totalGrade)
                .build();
    }

    /**
     * 提交学生评分
     *
     * @param teacherId          教师ID
     * @param studentId          学生ID
     * @param projectId          项目ID
     * @param gradeSubmissionDTO 评分信息
     */
    public void submitGrade(Long teacherId, Long studentId, Long projectId, GradeSubmissionDTO gradeSubmissionDTO) throws ServiceException {

        // 1. 检查教师是否负责该项目
        if (!projectTeacherRelationRepository.existsByTeacherIdAndProjectId(teacherId, projectId)) {
            throw new ServiceException("教师不负责该项目，无法评分");
        }
        // 2. 检查学生是否参与了该项目
        if (!volunteerProjectRelationRepository.existsByVolunteerIdAndProjectId(studentId, projectId)) {
            throw new ServiceException("学生未参与该项目，无法评分");
        }

        Optional<GradeSubmission> existingGradeSubmission = gradeSubmissionRepository.findByTeacherIdAndVolunteerIdAndProjectId(teacherId, studentId, projectId);

        GradeSubmission gradeSubmission;// 保存新记录
        if (existingGradeSubmission.isPresent()) {
            // 更新评分记录
            gradeSubmission = existingGradeSubmission.get();
        } else {
            // 创建新的评分记录
            gradeSubmission = new GradeSubmission();
            gradeSubmission.setTeacherId(teacherId);
            gradeSubmission.setVolunteerId(studentId);
            gradeSubmission.setProjectId(projectId);
        }
        gradeSubmission.setScore(gradeSubmissionDTO.getScore());
        gradeSubmission.setComments(gradeSubmissionDTO.getComments());
        gradeSubmissionRepository.save(gradeSubmission); // 保存更新后的记录

    }

    /**
     * 获取指定项目下所有学生的评分
     *
     * @param teacherId 教师ID
     * @param projectId 项目ID
     * @return 学生的评分信息列表
     * @throws ServiceException
     */
    public List<GradeSubmission> getGradesForProject(Long teacherId, Long projectId) throws ServiceException {
        // 1. 检查教师是否负责该项目
        if (projectTeacherRelationRepository.existsByTeacherIdAndProjectId(teacherId, projectId)) {
            throw new ServiceException("教师不负责该项目，无法查看评分");
        }

        // 2. 获取该项目下所有学生的评分
        List<GradeSubmission> grades = gradeSubmissionRepository.findByProjectId(projectId);

        // 如果没有评分记录，抛出异常
        if (grades.isEmpty()) {
            throw new ServiceException("该项目没有评分记录");
        }

        return grades;
    }
}
